package com.code.bz.services.impl;

import com.code.bz.daos.robot.RobotTaskCheckMapper;
import com.code.bz.managers.HttpManager;
import com.code.bz.models.qo.RobotTaskCheckQO;
import com.code.bz.services.ChatLinkService;
import com.code.bz.services.ChatTwitterService;
import com.code.bz.services.RobotSystemService;
import com.code.bz.services.RobotTaskCheckService;
import com.code.bz.utils.TimeUtil;
import com.code.consts.CommonConsts;
import com.code.enums.RewardKeyEnum;
import com.code.models.robot.RobotChatFinishTask;
import com.code.models.robot.RobotCheckPic;
import com.code.models.robot.RobotTaskCheck;
import com.code.models.robot.RobotTaskCheckContent;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 机器人任务审核服务实现类
 *
 * @author xiaoyaowang
 */
@Service
public class RobotTaskCheckServiceImpl implements RobotTaskCheckService {

    @Resource
    RobotTaskCheckMapper robotTaskCheckMapper;

    @Resource
    RobotSystemService robotSystemService;

    @Resource
    ChatLinkService chatLinkService;

    @Resource
    ChatTwitterService chatTwitterService;

    @Resource
    HttpManager httpManager;

    @Value("${isAddBzExperience}")
    private Boolean isAddBzExperience;

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = CommonConsts.TRANSACTION_MANAGER)
    public int updateRobotTaskState(RobotTaskCheck robotTaskCheckQuery) {
        Integer id = robotTaskCheckQuery.getId();
        RobotTaskCheck robotTaskCheck = robotTaskCheckMapper.getRobotTaskCheckById(id);
        if (null != robotTaskCheck) {
            Integer state = robotTaskCheckQuery.getState();
            if (null == state) {
                state = 0;
            }
            String chatId = robotTaskCheck.getChatId();
            if (state == 0) {
                if (null != robotTaskCheckMapper.existsChatBanByChatId(chatId)) {
                    robotTaskCheckMapper.deleteChatBanByChatId(chatId);
                }
                return robotTaskCheckMapper.updateRobotTaskState(id, state, new Date());
            }
            // 审核成功，本人获取400TP，如果被邀请人也审核成功，则还可以额外获取100TP
            if (state == 2) {
                int count = robotTaskCheckMapper.updateRobotTaskState(id, state, new Date());
                if (count > 0) {
                    if (isAddBzExperience) {
                        //BZ给用户生成一笔订单600U的BZ计划-体验计划（国际化）
                        count += httpManager.addBzExperience(robotTaskCheck.getBzAccount());
                    }
                }
                return count;
            }
            // 审核失败
            if (state == 1) {
                // 删除第六步任务
                Integer sixthTaskId = robotTaskCheckMapper.getTaskIdBySort(6);
                RobotChatFinishTask robotChatFinishSixthTaskDb = robotTaskCheckMapper.getRobotChatFinishTaskByChatIdAndTaskId(chatId, sixthTaskId);
                if (null != robotChatFinishSixthTaskDb) {
                    robotTaskCheckMapper.deleteRobotChatFinishTask(robotChatFinishSixthTaskDb);
                }
                // 第一步：（第五步任务）删除用户之前完成的发送不合格截图任务
                Integer fifthTaskId = robotTaskCheckMapper.getTaskIdBySort(5);
                RobotChatFinishTask robotChatFinishFifthTaskDb = robotTaskCheckMapper.getRobotChatFinishTaskByChatIdAndTaskId(chatId, fifthTaskId);
                if (null != robotChatFinishFifthTaskDb) {
                    robotTaskCheckMapper.deleteRobotChatFinishTask(robotChatFinishFifthTaskDb);
                }
                // 第二步：（第五步任务）删除审核记录和图片审核记录
                if (null != robotTaskCheckMapper.selectRobotTaskCheckById(id)) {
                    robotTaskCheckMapper.deleteRobotTaskCheckById(id);
                }
                List<RobotTaskCheckContent> robotTaskCheckContentList = robotTaskCheckMapper.getRobotTaskCheckContentListByTaskCheckId(id);
                if (!CollectionUtils.isEmpty(robotTaskCheckContentList)) {
                    robotTaskCheckMapper.deleteRobotTaskCheckContentList(robotTaskCheckContentList);
                }
                // 第四步：（第4步任务）删除关注推特的相关信息
                chatTwitterService.deleteChatTwitterByChatId(chatId);
                Integer fourthTaskId = robotTaskCheckMapper.getTaskIdBySort(4);
                RobotChatFinishTask robotChatFinishFourthTaskDb = robotTaskCheckMapper.getRobotChatFinishTaskByChatIdAndTaskId(chatId, fourthTaskId);
                if (null != robotChatFinishFourthTaskDb) {
                    robotTaskCheckMapper.deleteRobotChatFinishTask(robotChatFinishFourthTaskDb);
                }
                // （第三步任务）删除第三步任务完成记录
                Integer thirdTaskId = robotTaskCheckMapper.getTaskIdBySort(3);
                RobotChatFinishTask robotChatFinishThirdTaskDb = robotTaskCheckMapper.getRobotChatFinishTaskByChatIdAndTaskId(chatId, thirdTaskId);
                if (null != robotChatFinishThirdTaskDb) {
                    robotTaskCheckMapper.deleteRobotChatFinishTask(robotChatFinishThirdTaskDb);
                }
                // （第4步任务和第二步任务）删除关注推特的链接相关信息
                chatLinkService.deleteChatLinkByChatId(chatId);
                // （第二步任务）删除第二步任务完成记录
                Integer secondTaskId = robotTaskCheckMapper.getTaskIdBySort(2);
                RobotChatFinishTask robotChatFinishSecondTaskDb = robotTaskCheckMapper.getRobotChatFinishTaskByChatIdAndTaskId(chatId, secondTaskId);
                if (null != robotChatFinishSecondTaskDb) {
                    robotTaskCheckMapper.deleteRobotChatFinishTask(robotChatFinishSecondTaskDb);
                }
                // 最后一步：任务机器人向用户发送重新发送图片截图的任务
                String failureInfo = robotTaskCheckQuery.getFailureInfo();
                if (StringUtils.isBlank(failureInfo)) {
                    failureInfo = robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.SEND_PHOTO_TASK.name());
                }
                httpManager.sendReSendPhoto(Long.parseLong(chatId), failureInfo);
                return 0;
            }
        }
        return 0;
    }

    @Override
    public PageInfo<RobotTaskCheck> getRobotTaskCheckListByPage(RobotTaskCheckQO robotTaskCheckQO) {
        Integer sort = robotTaskCheckQO.getSort();
        if (null == sort) {
            robotTaskCheckQO.setSort(2);
        }
        Integer pageNum = robotTaskCheckQO.getPageNum();
        Integer pageSize = robotTaskCheckQO.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<RobotTaskCheck> list = robotTaskCheckMapper.getRobotTaskCheckListByPage(robotTaskCheckQO);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                if (null != robotTaskCheckMapper.existsChatBanByChatId(item.getChatId())) {
                    item.setState(3);
                }
            });
        }
        return PageInfo.of(list);
    }

    @Override
    public RobotTaskCheck getRobotTaskCheckById(int id) {
        RobotTaskCheck robotTaskCheck = robotTaskCheckMapper.getRobotTaskCheckById(id);
        if (null != robotTaskCheck) {
            String chatId = robotTaskCheck.getChatId();
            if (null != robotTaskCheckMapper.existsChatBanByChatId(chatId)) {
                robotTaskCheck.setState(3);
            }
            List<String> groupLinkList = chatLinkService.getChatLinkListByChatIdAndLinkCategory(chatId, 1);
            if (!CollectionUtils.isEmpty(groupLinkList)) {
                robotTaskCheck.setGroupShareLink(groupLinkList);
            }
            List<String> twitterLinkList = chatLinkService.getChatLinkListByChatIdAndLinkCategory(chatId, 2);
            if (!CollectionUtils.isEmpty(twitterLinkList)) {
                robotTaskCheck.setTwitterShareLink(twitterLinkList.get(0));
            }
            List<RobotTaskCheckContent> robotTaskCheckContentList = robotTaskCheckMapper.getRobotTaskCheckContentListByTaskCheckId(id);
            if (!CollectionUtils.isEmpty(robotTaskCheckContentList)) {
                int size = robotTaskCheckContentList.size();
                List<RobotCheckPic> robotCheckPicList = new ArrayList<>(size);
                RobotCheckPic robotCheckPic;
                List<RobotTaskCheckContent> robotTasList;
                Set<String> createAtSet = new HashSet<>(size);
                for (RobotTaskCheckContent robotTaskCheckContent : robotTaskCheckContentList) {
                    String createAtStr = TimeUtil.getLocalDateStr(robotTaskCheckContent.getCreatedAt(), TimeUtil.Y_M_D);
                    if (createAtSet.contains(createAtStr)) {
                        continue;
                    }
                    createAtSet.add(createAtStr);
                    robotCheckPic = new RobotCheckPic();
                    robotCheckPic.setCreateAt(createAtStr);
                    robotTasList = robotTaskCheckContentList.stream().filter(item ->
                            createAtStr.equals(TimeUtil.getLocalDateStr(item.getCreatedAt(), TimeUtil.Y_M_D))
                    ).collect(Collectors.toList());
                    List<String> picUrlList = new ArrayList<>(size);
                    robotTasList.forEach(items -> {
                        String picUrl = items.getPicUrl();
                        picUrlList.add(picUrl);
                    });
                    robotCheckPic.setPicUrlList(picUrlList);
                    robotCheckPicList.add(robotCheckPic);
                }
                createAtSet.clear();
                robotTaskCheck.setRobotCheckPicList(robotCheckPicList);
            }
        }
        return robotTaskCheck;
    }

    @Override
    public Integer getRobotState() {
        String robotStatus = robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.STOP_ROBOT.name());
        if (StringUtils.isBlank(robotStatus)) {
            robotStatus = "0";
        }
        return Integer.parseInt(robotStatus);
    }

}
